package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SmsTemplate smsTemplate;
    @Override
    public void sendMsg(String phone) {
//发送短信
        //1. 生成6位数验证码
        //todo 为了开发测试方便,临时写死验证码
        //String code = RandomUtil.randomNumbers(6);

        String code = "123";
        System.out.println("生成的验证码是:" + code);

        //2. 调用reids保存一下
        redisTemplate.opsForValue().set("CODE_" + phone, code, 5, TimeUnit.MINUTES);

        //3. 调用阿里云发送
        //todo 开发期间,为了省钱,暂时注释
        //smsTemplate.sendSms(phone, code);
    }

    @Autowired
    private UserMapper userMapper;
    //登录
    @Override
    public ResultInfo login(String phone, String code) {
        //1对比验证码,比对失败,返回错误提示
        String codeFromRedis = (String) redisTemplate.opsForValue().get("CODE_" + phone);
        if (!StringUtils.equals(code,codeFromRedis)) {
            return ResultInfo.error("验证码错误");
        }

        //2.根据手机号从数据库中查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userMapper.selectOne(queryWrapper);
//如果查询到了代表成功
        if (user != null) {
            if (user.getStatus() != 1) {
                return ResultInfo.error("您所输入的用户已被冻结");
            }
        } else {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }


        //生成token
       Map map = new HashMap<>();
        map.put("id", user.getId());
        String token = JwtUtil.createToken(map);
        //将token和用户信息保存到redis
       redisTemplate.opsForValue().set("TOKEN_"+token,user,1,TimeUnit.DAYS);

        return ResultInfo.success( token);
    }

    @Override
    public void delete(String token) {
        redisTemplate.delete("TOKEN_" + token);
        log.info("退出登录成功");
    }


}
